import { observable, action } from 'mobx';
import { list, del, modify } from "../apis/template";

export default class TemplateStore {
    @observable templates = []; // 模板列表数据
    @observable sysTmpNums = 0; // 系统默认模板的数量
    @observable customTmpNums = 0; // 自定义模板的数量
    @observable currPage = 1; // 当前页
    @observable searchText = ""; // 模板搜索的关键字
    @observable pageSize = 10; // 每页显示模板的数量
    @observable isImport = false; // 是否显示模板导入
    @observable currTemplate = null; // 当前正在编辑的模板
    @observable type = 0; // 模板类型 0全部 1系统默认 2自定义

    constructor() {}

    // 获取模板列表
    @action getTmpList = () => {
        const store = this;

        list().then(result => {
            const len = result.data.length;

            if(!len) return;
            let sysTmpNums = 0;

            result.data.forEach(tmp => {
                tmp.issys && sysTmpNums++;
            });
            store.templates = result.data;
            store.sysTmpNums = sysTmpNums;
            store.customTmpNums = len - sysTmpNums;
        });
    }

    // 删除模板
    @action onDelete = tmpId => {
        const store = this;

        del(tmpId).then(()=>{
            store.templates = store.templates.filter( template => {
                if(tmpId != template.id) return template;
                if(template.issys) {
                    store.sysTmpNums--;
                } else {
                    store.customTmpNums--;
                }
            });
        });
    }

    // 修改模板信息
    @action onModify = template => {
        return modify(template);
    }

    // 模板搜索的关键字变更
    @action onSearchTextChange = searchText => {
        this.searchText = searchText;
    }

    // 模板类型更换
    @action onTypeChange = type => {
        this.type = type;
        this.onCurrpageChange(1);
    }

    // 显示数量改变
    @action onShowSizeChange = pageSize => {
        this.pageSize = pageSize;
        this.onCurrpageChange(1);
    }

    // 当前页改变
    @action onCurrpageChange = currPage => {
        this.currPage = currPage || 1;
    }

    // 控制导入窗口的显隐
    @action toggleImport = isImport => {
        this.isImport = isImport;
    }

    // 控制模板编辑窗口的显隐
    @action toggleEdit = template => {
        this.currTemplate = template;
    }
}